#!/usr/bin/env bash
# Usage: swiftenv global [<version>]
# Summary: Set or show the global Swift version
# completes

set -e

if [ "$1" = "--complete" ]; then
  echo "system"
  exec swiftenv-versions --bare
fi

VERSION=$1
VERSION_FILE="$SWIFTENV_ROOT/version"

version_exists() {
  local version="$1"
  [ -d "$SWIFTENV_ROOT/versions/$version" ] || [ -d "/Library/Developer/Toolchains/$version.xctoolchain" ]
}

if [ -z "$VERSION" ]; then
  if [ -f "$VERSION_FILE" ]; then
    cat "$VERSION_FILE"
  else
    echo "swiftenv: version is not set"
    exit 1
  fi
elif swiftenv-prefix "$VERSION" >/dev/null || [ "$VERSION" == "system" ]; then
  echo "$VERSION" > "$VERSION_FILE"
else
  echo "swiftenv: version \`$VERSION' is not installed"
  exit 1
fi
